package org.example.user.aspect;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.example.common.enums.LogAsync;
import org.example.common.utils.SessionUtil;
import org.example.user.entity.SysLogEntity;
import org.example.user.service.ISysLogService;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.Task;
import org.springframework.stereotype.Component;
import org.springframework.scheduling.annotation.Async;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

@Aspect
@Component
@Slf4j
public class LogAspect {

    @Autowired
    private ISysLogService sysLogService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    Executor taskExecutor;

    // 定义切点：标注@LogAsync的方法
    @Pointcut("@annotation(org.example.common.enums.LogAsync)")
    public void logPointcut() {}

    // 环绕通知实现日志记录
    @Around("logPointcut()")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        LogAsync logAnnotation = signature.getMethod().getAnnotation(LogAsync.class);

        // 记录方法开始执行时间
        long startTime = System.currentTimeMillis();
        Object result = null;
        try {
            // 执行目标方法
            result = joinPoint.proceed();
        } finally {
            // 在主线程中提前获取请求信息
            String clientIp = getClientIp();
            Long userId = getCurrentUserId();

            // 异步记录日志（不会阻塞主线程）
            asyncRecordLog(joinPoint, logAnnotation, startTime, result, clientIp, userId);
        }
        return result;
    }

    // 异步日志记录方法
    public void asyncRecordLog(ProceedingJoinPoint joinPoint,
                               LogAsync logAnnotation,
                               long startTime,
                               Object result,
                               String clientIp,
                               Long userId) {

        taskExecutor.execute(new Runnable(){
            @Override
            public void run() {
                long executionTime = System.currentTimeMillis() - startTime;
                MethodSignature signature = (MethodSignature) joinPoint.getSignature();
                String className = joinPoint.getTarget().getClass().getName();
                String methodName = signature.getName();
                Object[] args = joinPoint.getArgs();

                // 构建日志内容
                StringBuilder logContent = new StringBuilder();
                logContent.append("【").append(logAnnotation.value()).append("】")
                        .append(" 执行时间: ").append(executionTime).append("ms | ")
                        .append("类: ").append(className)
                        .append(" | 方法: ").append(methodName);

                if (logAnnotation.recordParams()) {
                    logContent.append(" | 参数: ");
                    for (Object arg : args) {
                        logContent.append(arg).append(", ");
                    }
                    if (args.length > 0) {
                        logContent.delete(logContent.length() - 2, logContent.length());
                    }
                }

                SysLogEntity logEntity = new SysLogEntity();
                logEntity.setAction(logAnnotation.value());
                logEntity.setDetail(JSONObject.toJSONString(logContent));
                logEntity.setIp(clientIp); // 使用传递进来的IP地址
                logEntity.setCreatedTime(new Date());
                logEntity.setUserId(userId); // 使用传递进来的用户ID
                logEntity.setTargetId(null);
                logEntity.setTargetType("user");

                sysLogService.save(logEntity);

                // 实际日志输出（可根据需要存入数据库）
                log.info(logContent.toString());
            }
        });

    }

    // 获取客户端IP地址的方法
    private String getClientIp() {
        try {
            return request.getRemoteAddr();
        } catch (Exception e) {
            return "unknown";
        }
    }

    // 获取当前用户ID的方法
    private Long getCurrentUserId() {
        try {
            return SessionUtil.getSysUser().getUserId();
        } catch (Exception e) {
            return null;
        }
    }
}
